/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
package example.springboot.service;

import example.springboot.dto.WordbookDTO;
import example.springboot.entity.Wordbook;
import example.springboot.mapper.WordbookMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class WordbookService {

    @Autowired
    private WordbookMapper wordbookMapper;

    /**
     * 根据ID查询词书
     */
    public Wordbook findById(Integer id) {
        return wordbookMapper.findById(id);
    }

    /**
     * 获取所有词书列表
     */
    public List<WordbookDTO> getAllWordbooks() {
        List<Wordbook> wordbooks = wordbookMapper.findAll();
        
        // 转换为DTO，并添加统计信息
        return wordbooks.stream().map(wordbook -> {
            WordbookDTO dto = new WordbookDTO();
            BeanUtils.copyProperties(wordbook, dto);
            
            // 查询单词数量
            Integer wordCount = wordbookMapper.countWordsByWordbookId(wordbook.getId());
            dto.setWordCount(wordCount != null ? wordCount : 0);
            
            // 查询学习人数
            Integer userCount = wordbookMapper.countUsersByWordbookId(wordbook.getId());
            dto.setUserCount(userCount != null ? userCount : 0);
            
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 创建词书
     */
    public Wordbook createWordbook(Wordbook wordbook) {
        wordbookMapper.insert(wordbook);
        return wordbook;
    }

    /**
     * 更新词书
     */
    public boolean updateWordbook(Wordbook wordbook) {
        Wordbook existWordbook = wordbookMapper.findById(wordbook.getId());
        if (existWordbook == null) {
            throw new RuntimeException("词书不存在");
        }
        
        return wordbookMapper.update(wordbook) > 0;
    }

    /**
     * 删除词书
     */
    public boolean deleteWordbook(Integer id) {
        return wordbookMapper.deleteById(id) > 0;
    }

    /**
     * 根据词书ID查询单词列表
     */
    public List<example.springboot.entity.Word> getWordsByWordbookId(Integer wordbookId) {
        return wordbookMapper.findWordsByWordbookId(wordbookId);
    }

    /**
     * 从词书中移除单词
     */
    public boolean removeWordFromWordbook(Integer wordbookId, Integer wordId) {
        return wordbookMapper.removeWordFromWordbook(wordbookId, wordId) > 0;
    }
}

